package com.service.business.banklock.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.service.business.banklock.controller.rep.MemberBankLockRep;
import com.service.business.banklock.controller.req.MemberBankLockDetailsReq;
import com.service.business.banklock.controller.req.MemberBankLockReq;
import com.service.business.banklock.controller.req.PageBankLockReq;
import com.service.business.banklock.service.MemberBankLockService;
import com.service.business.borrow.controller.rep.MemberBorrowDetailsRep;
import com.service.business.member.dto.MemberStoreChange;
import com.service.business.member.service.MemberStoreService;
import com.service.business.support.Language;
import com.service.business.support.MemberStoreLockUtils;
import com.service.business.support.SessionUtil;
import com.service.business.utils.DateUtil;
import com.service.business.utils.I18nUtil;
import com.service.core.exception.CommonException;
import com.service.core.rest.response.CommonPageRep;
import com.service.dao.enums.MemberJAType;
import com.service.dao.mapper.MemberBankLockMapper;
import com.service.dao.mapper.MemberBankLockTypeMapper;
import com.service.dao.model.MemberBankLock;
import com.service.dao.model.MemberBankLockType;
import com.service.dao.model.MemberBorrow;
import com.service.dao.model.MemberStore;
import com.service.utility.modelmapper.ModelMapperUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class MemberBankLockServiceImpl extends ServiceImpl<MemberBankLockMapper, MemberBankLock> implements MemberBankLockService {

	@Autowired
	private MemberBankLockTypeMapper memberBankLockTypeMapper;

	@Autowired
	private SessionUtil sessionUtil;

	@Autowired
	private MemberStoreLockUtils memberStoreLockUtils;

	@Autowired
	private MemberStoreService memberStoreService;

	/**
	 * 新增锁仓
	 *
	 * @param req
	 * @return
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void addLock(MemberBankLockReq req) {
		Integer memberId = sessionUtil.getUser().getUserId();
		MemberBankLockType lockType = memberBankLockTypeMapper.selectById(req.getLockTypeId());
		if (ObjectUtils.isEmpty(lockType)) {
			log.error("日期：{}，用户<{}>锁仓类型未找到", DateUtil.getOnlyDay(new Date()), memberId);
			return;
		} else {
			boolean isLock = memberStoreLockUtils.lock(memberId, req.getCoinsId());
			if (!isLock) {
				return;
			}
			//获取用户对应的账户的余额
			MemberStore memberStore = memberStoreService.getMemberStore(memberId, req.getCoinsName());
			if (ObjectUtils.isEmpty(memberStore)) {
				String msg = I18nUtil.getMessage("store_balance_exception_not_enough", Language.LANG.get(), req.getCoinsName());
				throw new CommonException(msg);
			}
			BigDecimal num = memberStore.getNum();
			if (num.compareTo(req.getLockNum()) < 0) {
				String msg = I18nUtil.getMessage("store_balance_exception_not_enough", Language.LANG.get(), req.getCoinsName());
				throw new CommonException(msg);
			} else {
				//执行锁仓 冻结余额操作
				memberStoreService.changeMemberStore(
						MemberStoreChange.builder()
								.memberId(memberId)
								.coinsId(req.getCoinsId())
								.coinsName(req.getCoinsName())
								.jaType(MemberJAType.MEMBER_BANK_LOCK)
								.changeNum(req.getLockNum())
								.remark(memberId + MemberJAType.MEMBER_BANK_LOCK.getMsg().toString())
								.build());
				memberStoreLockUtils.unlock(memberId, req.getCoinsId());
			}
		}
	}

	/**
	 * 锁仓列表
	 *
	 * @param req
	 * @return
	 */
	@Override
	public CommonPageRep<MemberBankLockRep> listLock(PageBankLockReq req) {
		Integer memberId = sessionUtil.getUser().getUserId();
		Page<MemberBankLock> page = PageHelper.startPage(req.getPageNo(), req.getPageSize());
		List<MemberBankLockRep> list = baseMapper.selectList(new LambdaQueryWrapper<MemberBankLock>()
				.eq(MemberBankLock::getMemberId, memberId)
				.orderByDesc(MemberBankLock::getUpdateTime))
				.stream().map(item -> ModelMapperUtil.map(item, MemberBankLockRep.class))
				.collect(Collectors.toList());
		list.forEach(item -> {
			item.setUserName(sessionUtil.getUser().getUsername());
			item.setMobile(sessionUtil.getUser().getMobile());
		});
		return CommonPageRep.buildResultRep(page, list);
	}

	/**
	 * 获取锁仓记录详情
	 *
	 * @param req
	 * @return
	 */
	@Override
	public MemberBankLockRep details(MemberBankLockDetailsReq req) {
		MemberBankLock bankLock = baseMapper.selectById(req.getLockId());
		if (ObjectUtils.isEmpty(bankLock)) {
			return null;
		} else {
			MemberBankLockRep rep = new MemberBankLockRep();
			ModelMapperUtil.map(bankLock, MemberBankLockRep.class);
			rep.setUserName(sessionUtil.getUser().getUsername());
			rep.setMobile(sessionUtil.getUser().getMobile());
			return rep;
		}
	}

}
